package tjs.styudy.mini.springboot.transaction.config;

import java.sql.Connection;

/**
 * Created by Nicky.Tang on 2021/10/27 9:46 下午
 *
 * @since 02.12.10
 */
public class ConnectionHolder {
    private static final ThreadLocal<ConnectionHolder> CONNECTION_THREAD_LOCAL = new ThreadLocal<>();

    // 当前的
    private Connection curConnection;

    // 上一个方法的
    private ConnectionHolder lastConnectionHolder;

    // 释放资源
    public static void unbindResource() {
        ConnectionHolder lastConnectionHolder = CONNECTION_THREAD_LOCAL.get();
        if (lastConnectionHolder == null) {
            return;
        }
        // 重置当前连接为上一个方法的连接
        // 第一个ConnectionHolder的lastConnectionHolder属性为null，间接释放资源
        CONNECTION_THREAD_LOCAL.set(lastConnectionHolder.getLastConnectionHolder());
    }

    // 获取资源
    public static ConnectionHolder getResource() {
        return CONNECTION_THREAD_LOCAL.get();
    }

    // 绑定(set)资源
    public static void bindResource(ConnectionHolder connectionHolder) {
        CONNECTION_THREAD_LOCAL.set(connectionHolder);
    }

    public static Connection getCurConnectionStatic() {
        ConnectionHolder connectionHolder = ConnectionHolder.getResource();
        return connectionHolder != null ? connectionHolder.getCurConnection() : null;
    }

    public Connection getCurConnection() {
        return curConnection;
    }

    public void setCurConnection(Connection curConnection) {
        this.curConnection = curConnection;
    }

    public ConnectionHolder getLastConnectionHolder() {
        return lastConnectionHolder;
    }

    public void setLastConnectionHolder(ConnectionHolder lastConnectionHolder) {
        this.lastConnectionHolder = lastConnectionHolder;
    }
}
